package com.itjin.resume_back.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itjin.resume_back.common.Result;
import com.itjin.resume_back.entity.Project;
import com.itjin.resume_back.entity.Resume;
import com.itjin.resume_back.entity.User;
import com.itjin.resume_back.service.ProjectService;
import com.itjin.resume_back.service.ResumeService;
import com.itjin.resume_back.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 管理员控制器
 * 提供管理员相关的接口，包括用户管理、简历审核、项目审核等功能
 */
@Tag(name = "管理员接口", description = "管理员相关的接口，包括用户管理、简历审核、项目审核等功能")
@RestController
@RequestMapping("/api/admin")
@RequiredArgsConstructor
public class AdminController {

  private final UserService userService;
  private final ResumeService resumeService;
  private final ProjectService projectService;

  /**
   * 获取用户列表
   * 
   * @param page 页码
   * @param size 每页大小
   * @return 分页用户列表
   */
  @Operation(summary = "获取用户列表", description = "分页获取所有用户信息")
  @GetMapping("/users")
  public Result<Page<User>> listUsers(
      @Parameter(description = "页码", required = true) @RequestParam(value = "page", defaultValue = "1") Integer page,
      @Parameter(description = "每页大小", required = true) @RequestParam(value = "size", defaultValue = "10") Integer size) {
    try {
      Page<User> pageParam = new Page<>(page, size);
      LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
      wrapper.orderByDesc(User::getCreateTime);
      Page<User> userPage = userService.page(pageParam, wrapper);

      // 安全考虑，清除密码
      userPage.getRecords().forEach(user -> user.setPassword(null));

      return Result.success(userPage);
    } catch (Exception e) {
      return Result.error(e.getMessage());
    }
  }

  /**
   * 更新用户状态
   * 
   * @param userId 用户ID
   * @param status 新状态
   * @return 操作结果
   */
  @Operation(summary = "更新用户状态", description = "更新指定用户的状态")
  @PutMapping("/user/status")
  public Result<String> updateUserStatus(
      @Parameter(description = "用户ID", required = true) @RequestParam("userId") Long userId,
      @Parameter(description = "新状态", required = true) @RequestParam("status") Integer status) {
    try {
      userService.updateStatus(userId, status);
      return Result.success("用户状态更新成功");
    } catch (Exception e) {
      return Result.error(e.getMessage());
    }
  }

  /**
   * 获取简历列表
   * 
   * @param page       页码
   * @param size       每页大小
   * @param isApproved 审核状态（可选）
   * @return 分页简历列表
   */
  @Operation(summary = "获取简历列表", description = "分页获取所有简历信息，可按审核状态筛选")
  @GetMapping("/resumes")
  public Result<Page<Resume>> listResumes(
      @Parameter(description = "页码", required = true) @RequestParam(value = "page", defaultValue = "1") Integer page,
      @Parameter(description = "每页大小", required = true) @RequestParam(value = "size", defaultValue = "10") Integer size,
      @Parameter(description = "审核状态", required = false) @RequestParam(value = "isApproved", required = false) Integer isApproved) {
    try {
      Page<Resume> pageParam = new Page<>(page, size);
      LambdaQueryWrapper<Resume> wrapper = new LambdaQueryWrapper<>();

      if (isApproved != null) {
        wrapper.eq(Resume::getIsApproved, isApproved);
      }

      wrapper.orderByDesc(Resume::getCreateTime);
      Page<Resume> resumePage = resumeService.page(pageParam, wrapper);
      return Result.success(resumePage);
    } catch (Exception e) {
      return Result.error(e.getMessage());
    }
  }

  /**
   * 审核简历
   * 
   * @param id     简历ID
   * @param status 审核状态
   * @return 操作结果
   */
  @Operation(summary = "审核简历", description = "更新简历的审核状态")
  @PutMapping("/resume/approve")
  public Result<String> approveResume(
      @Parameter(description = "简历ID", required = true) @RequestParam("id") Long id,
      @Parameter(description = "审核状态", required = true) @RequestParam("status") Integer status) {
    try {
      resumeService.approveResume(id, status);
      return Result.success("简历审核状态更新成功");
    } catch (Exception e) {
      return Result.error(e.getMessage());
    }
  }

  /**
   * 获取项目列表
   * 
   * @param page       页码
   * @param size       每页大小
   * @param isApproved 审核状态（可选）
   * @return 分页项目列表
   */
  @Operation(summary = "获取项目列表", description = "分页获取所有项目信息，可按审核状态筛选")
  @GetMapping("/projects")
  public Result<Page<Project>> listProjects(
      @Parameter(description = "页码", required = true) @RequestParam(value = "page", defaultValue = "1") Integer page,
      @Parameter(description = "每页大小", required = true) @RequestParam(value = "size", defaultValue = "10") Integer size,
      @Parameter(description = "审核状态", required = false) @RequestParam(value = "isApproved", required = false) Integer isApproved) {
    try {
      Page<Project> pageParam = new Page<>(page, size);
      LambdaQueryWrapper<Project> wrapper = new LambdaQueryWrapper<>();

      if (isApproved != null) {
        wrapper.eq(Project::getIsApproved, isApproved);
      }

      wrapper.orderByDesc(Project::getCreateTime);
      Page<Project> projectPage = projectService.page(pageParam, wrapper);
      return Result.success(projectPage);
    } catch (Exception e) {
      return Result.error(e.getMessage());
    }
  }

  /**
   * 审核项目
   * 
   * @param id     项目ID
   * @param status 审核状态
   * @return 操作结果
   */
  @Operation(summary = "审核项目", description = "更新项目的审核状态")
  @PutMapping("/project/approve")
  public Result<String> approveProject(
      @Parameter(description = "项目ID", required = true) @RequestParam("id") Long id,
      @Parameter(description = "审核状态", required = true) @RequestParam("status") Integer status) {
    try {
      projectService.approveProject(id, status);
      return Result.success("项目审核状态更新成功");
    } catch (Exception e) {
      return Result.error(e.getMessage());
    }
  }

  /**
   * 获取统计数据
   * 
   * @return 包含用户数、简历数、项目数等统计信息
   */
  @Operation(summary = "获取统计数据", description = "获取系统统计数据，包括用户数、简历数、项目数等")
  @GetMapping("/statistics")
  public Result<Map<String, Object>> getStatistics() {
    try {
      Map<String, Object> statistics = new HashMap<>();

      // 用户总数
      long userCount = userService.count();
      statistics.put("userCount", userCount);

      // 简历总数
      long resumeCount = resumeService.count();
      statistics.put("resumeCount", resumeCount);

      // 项目总数
      long projectCount = projectService.count();
      statistics.put("projectCount", projectCount);

      // 待审核简历数
      long pendingResumeCount = resumeService.count(
          new LambdaQueryWrapper<Resume>().eq(Resume::getIsApproved, 0));
      statistics.put("pendingResumeCount", pendingResumeCount);

      // 待审核项目数
      long pendingProjectCount = projectService.count(
          new LambdaQueryWrapper<Project>().eq(Project::getIsApproved, 0));
      statistics.put("pendingProjectCount", pendingProjectCount);

      return Result.success(statistics);
    } catch (Exception e) {
      return Result.error(e.getMessage());
    }
  }
}